package com.mediautils.photoutils;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import androidx.core.content.FileProvider;

import java.io.*;

public class PhotosTools {
    public static String urlAuthTag = "com.mediautils.photoutils.fileprovider";
    public static int takePhoto = 1; //requestCode
    public static Uri imageUri;
    private static File outputImage;
    public static int fromAlbum = 2; //requestCode

    /**
     * 相机图片返回
     *
     * @param context
     */
    public static void CameraResult(Activity context) {
        try {
            outputImage = new File(context.getExternalCacheDir(), "output_image.jpg");
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
            //创建File对象的Uri, 从Android 7.0开始，直接使用本地真实路径的Uri被认为是不安全的
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                imageUri = FileProvider.getUriForFile(context, urlAuthTag, outputImage);
            } else {
                imageUri = Uri.fromFile(outputImage);
            }
            //启动相机程序
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            context.startActivityForResult(intent, takePhoto);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Uri getPhotoUri(){
        return imageUri;
    }

    /**
     * 系统相册图片选择
     *
     * @param context
     */
    public static void SystemAlbumResult(Activity context) {
        //打开文件选择器
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        //指定只显示图片
        intent.setType("image/*");
        context.startActivityForResult(intent, fromAlbum);
    }

    public static Bitmap getBitmapFromUri(Activity context, Uri uri) {
        Bitmap mBitmap = null;
        try {
            ParcelFileDescriptor mFileDescriptor = context.getContentResolver().openFileDescriptor(uri, "r");
            mBitmap = BitmapFactory.decodeFileDescriptor(mFileDescriptor.getFileDescriptor());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return mBitmap;
    }

    public static Bitmap getBitmap(Activity context) {
        try {
            return rotateIfRequired(BitmapFactory.decodeStream(context.getContentResolver().openInputStream(imageUri)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断图片方向，如果图片需要旋转，就将图片旋转相应的角度
     */
    private static Bitmap rotateIfRequired(Bitmap bitmap) {
        try {
            ExifInterface exif = new ExifInterface(outputImage.getPath());
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                return rotateBitmap(bitmap, 90);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                return rotateBitmap(bitmap, 180);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                return rotateBitmap(bitmap, 270);
            } else {
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    /**
     * 旋转图片
     *
     * @param bitmap
     * @param degree
     * @return
     */
    private static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate((float) degree);
        Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
        bitmap.recycle();
        return rotatedBitmap;
    }
}
